package com.atguigu.connection;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author admin
 */
public class DBCPTest {

    /**
     * 测试 DBCP 的数据库连接池技术
     */
    /**
     * 方式一：不推荐
     *
     * @throws SQLException
     */
    @Test
    public void testGetConnection() throws SQLException {
        // 创建 DBCP 数据库连接池
        BasicDataSource source = new BasicDataSource();

        // 设置基本信息
        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUrl("jdbc:mysql:///atguigu_jdbc");
        source.setUsername("root");
        source.setPassword("123456");

        // 还可以设置其他涉及数据库连接池管理的相关属性
        source.setInitialSize(10);

        Connection connection = source.getConnection();
        System.out.println(connection);
    }

    /**
     * 方式二：使用配置文件
     */
    @Test
    public void testGetConnection1() throws Exception {
        Properties properties = new Properties();
        // 方式一：
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
        // 方式二：
        // FileInputStream inputStream = new FileInputStream(new File("resources/dbcp.properties"));
        properties.load(inputStream);

        BasicDataSource source = BasicDataSourceFactory.createDataSource(properties);
        Connection connection = source.getConnection();

        System.out.println(connection);
    }
}
